package cn.wowjoy.office.baselivedata.appbase;

import android.app.Activity;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.common.widget.MyToast;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.remote.ApiException;
import cn.wowjoy.office.data.remote.ERROR;
import cn.wowjoy.office.data.remote.ExceptionEgine;
import cn.wowjoy.office.databinding.ErrorViewBinding;
import cn.wowjoy.office.loginnew.LoginActivity;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;
import dagger.android.support.DaggerAppCompatActivity;

/**
 * Created by Sherily on 2017/12/18.
 * Description:
 */

public abstract class NewBaseActivity<DB extends ViewDataBinding, VM extends NewBaseViewModel> extends DaggerAppCompatActivity  {

    @Inject
    ViewModelProvider.Factory viewModelFactory;
    @Inject
    public PreferenceManager preferenceManager;

    private IntentFilter intentFilter;
    private ScanReceiver scanReceiver;



    public ScanReceiver getScanReceiver() {
        return scanReceiver;
    }


    protected VM viewModel;

    protected DB binding;

    protected abstract Class<VM> getViewModel();

    @LayoutRes
    protected abstract int getLayoutId();

    protected abstract void init(Bundle savedInstanceState);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        AndroidInjection.inject(this);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModel());
        binding = DataBindingUtil.setContentView(this, getLayoutId());
        this.init(savedInstanceState);
        initBroadCast();

   //     RxBus.getInstance().register(this);
//        setLight(this,55);



//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//            // 请注意这里会有一个版本适配bug，所以请在这里添加非空判断
//            if (connectivityManager != null) {
//                connectivityManager.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback() {
//
//                    /**
//                     * 网络可用的回调
//                     * */
//                    @Override
//                    public void onAvailable(Network network) {
//                        super.onAvailable(network);
//                        Log.e("lzp", "onAvailable");
//                    }
//
//                    /**
//                     * 网络丢失的回调
//                     * */
//                    @Override
//                    public void onLost(Network network) {
//                        super.onLost(network);
//                        Log.e("lzp", "onLost");
//                    }
//
//                    /**
//                     * 当建立网络连接时，回调连接的属性
//                     * */
//                    @Override
//                    public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
//                        super.onLinkPropertiesChanged(network, linkProperties);
//                        Log.e("lzp", "onLinkPropertiesChanged");
//                    }
//
//                    /**
//                     *  按照官方的字面意思是，当我们的网络的某个能力发生了变化回调，那么也就是说可能会回调多次
//                     *
//                     *  之后在仔细的研究
//                     * */
//                    @Override
//                    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
//                        super.onCapabilitiesChanged(network, networkCapabilities);
//                        Log.e("lzp", "onCapabilitiesChanged");
//                    }
//
//                    /**
//                     * 在网络失去连接的时候回调，但是如果是一个生硬的断开，他可能不回调
//                     * */
//                    @Override
//                    public void onLosing(Network network, int maxMsToLive) {
//                        super.onLosing(network, maxMsToLive);
//                        Log.e("lzp", "onLosing");
//                    }
//
//                    /**
//                     * 按照官方注释的解释，是指如果在超时时间内都没有找到可用的网络时进行回调
//                     * */
//                    @Override
//                    public void onUnavailable() {
//                        super.onUnavailable();
//                        Log.e("lzp", "onUnavailable");
//                    }
//
//                });
//            }
//        }
    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.unbind();
        viewModel.onDestroy();
    //    RxBus.getInstance().unRegister(this);
    }


    /***
     * 扫码逻辑模块：包括注册广播，撤销广播，及扫码实现逻辑
     */

    class ScanReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.BAR_ADD)) {
                new MyToast(context).showinfo(intent.getStringExtra(Constants.BAR_KEY));
                if (!"ERROR".equals(intent.getStringExtra(Constants.BAR_KEY))) {
                }
            } else if (intent.getAction().equals(Constants.RFID_ADD)) {
                new MyToast(context).showinfo(intent.getStringExtra(Constants.RFID_KEY));
                if (!"ERROR".equals(intent.getStringExtra(Constants.BAR_KEY))) {
                }
            } else if (intent.getAction().equals(Constants.WOW_ADD)) {
//                new MyToast(context).showinfo(intent.getStringExtra(Contants.WOW_KEY));
            } else if (intent.getAction().equals(Constants.WOW_NEW_ADD)) {
                String msg = intent.getStringExtra(Constants.WOW_NEW_KEY);
                brodcast(context, msg);
            }
        }
    }
    /**
     *扫码自定义逻辑
     * @param context
     * @param msg
     */
    protected void brodcast(Context context, String msg) {
        //实现扫码逻辑
    }


    /**
     * 每个页面需要广播时候开启注册广播
     */
    protected void openBroadCast(){
        registerReceiver(scanReceiver, intentFilter);
    }

    /**
     * 取消广播
     */
    protected void closeBroadCast(){
        unregisterReceiver(scanReceiver);
    }

    /**
     * 初始化广播
     */
    private void initBroadCast(){
        intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.BAR_ADD);
        intentFilter.addAction(Constants.RFID_ADD);
        intentFilter.addAction(Constants.WOW_ADD);
        intentFilter.addAction(Constants.WOW_NEW_ADD);
        scanReceiver = new ScanReceiver();
    }


    /**
     * 设置屏幕亮度
     * @param context
     * @param brightness
     */
    private void setLight(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
    }

    /**
     * 隐藏软键盘
     */
    protected void hideSoftInput(){
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.getRoot().getWindowToken(), 0);
    }

    /**
     * 显示和隐藏状态栏
     * @param show
     */
    protected void setStatusBarVisible(boolean show) {
        if (show) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    /***
     * 权限处理
     * @param permissions
     * @param requestCode
     * @return
     */
    protected boolean requestRuntimePermissions(final String[] permissions, final int requestCode) {
        boolean ret = true;
        for (String permission : permissions) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                ret &= (PermissionChecker.checkSelfPermission(this, permission) == PermissionChecker.PERMISSION_GRANTED);
            else
                ret &= (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED);
        }
        if (ret) {
            return true;
        }
        boolean rationale = false;
        for (String permission : permissions) {
            rationale |= ActivityCompat.shouldShowRequestPermissionRationale(NewBaseActivity.this,permission);

        }
        if (rationale) {
            Toast.makeText(this,"请开启权限后使用",Toast.LENGTH_SHORT).show();

        } else {
            ActivityCompat.requestPermissions(NewBaseActivity.this,permissions, requestCode);

        }
        return false;
    }




    /**
     * 异常处理
     */
    private ErrorViewBinding errorViewBinding;
    /**
     * baseActivity中handleException(Exception e,boolean needErrorView):
     *统一处理exception，当needErrorView = true,是，需要在getErrorview中返回承载errorview的布局，
     *目前支持Framelayout，可以覆盖后面的结果页面。当needErrorView = false,用toast的形式提醒错误，401的状态下统一跳转至LoginActivity
     * @param e
     * @param needErrorview
     */
    public void handleException(Throwable e,boolean needErrorview){
        ApiException apiException = ExceptionEgine.handleException(e);
        if (apiException.getCode() == ERROR.UNAUTHORIZED){
            ToastUtil.toastWarning(NewBaseActivity.this,e.getMessage(),-1);
//            new MyToast(this).showinfo(apiException.getMessage());
            preferenceManager.clearToken();
            LoginActivity.startAndClearTask(NewBaseActivity.this);

        } else {
            if (needErrorview){
                createErrorView(apiException);
            } else {
                ToastUtil.toastWarning(NewBaseActivity.this,e.getMessage(),-1);
//                new MyToast(NewBaseActivity.this).showinfo(e.getMessage());
            }

        }
    }


    /**
     * 在每个子activity中实现，哪一块区域需要用，就返回哪块，目前只考虑FrameLayout
     * @return
     */
    protected ViewGroup getErrorViewRoot(){

        return  null;
    }

    /**
     * 记住，记住，记住，在需要errorview通过 getErrorViewRoot()返回承载errorview的布局，目前支持Framelayout
     * @param e
     */
    private void createErrorView( ApiException e){
        if (null != getErrorViewRoot()){
            removeErrorview();
            hideSoftInput();
            LayoutInflater inflater =  LayoutInflater.from(getErrorViewRoot().getContext());
            errorViewBinding = DataBindingUtil.inflate(inflater, R.layout.error_view,getErrorViewRoot(),false);
            errorViewBinding.getRoot().setClickable(true);
            switch (e.getCode()){
                case 404:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.error_404,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                case 500:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.error_500,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                case 1002:
                    errorViewBinding.errorContent.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.wi_fi,0,0);
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
                default:
                    errorViewBinding.errorContent.setText(e.getMessage());
                    break;
            }
            errorViewBinding.errorContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshError();
                }
            });
            ViewGroup.LayoutParams layoutParams = getErrorViewRoot().getLayoutParams();
            getErrorViewRoot().addView(errorViewBinding.getRoot(),layoutParams);
        } else {
            //知道你们会忘记加布局，为了防止异常，有toast提醒
            ToastUtil.toastWarning(NewBaseActivity.this,e.getMessage(),-1);
//            new MyToast(NewBaseActivity.this).showinfo(e.getMessage());
        }


    }


    /**
     *在refreshError之后记住removeErroeView
     */
    public void removeErrorview(){

        if (null != getErrorViewRoot()){
            if (null != errorViewBinding)
                getErrorViewRoot().removeView(errorViewBinding.getRoot());
        }
    }

    /**
     * errorView添加后，点击error图片即可重新请求相应的接口，进行处理
     */
    protected void refreshError(){
        removeErrorview();
        //具体页面实现请求对应接口渲染数据
    }



}
